package com.blb.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.blb.entity.Menu;
import com.blb.entity.Role;
import com.blb.entity.User;
import com.blb.entity.page.BlbPage;
import com.blb.entity.page.DataTablePage;
import com.blb.service.IMenuService;
import com.blb.service.IRoleService;
import com.blb.service.IUserService;
import com.blb.utils.ResponseHelp;
import com.blb.utils.ShiroUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author QuJiaHao
 * @since 2019-11-16
 */
@Controller
@RequestMapping("/role")
public class RoleController {
    @Resource
    private IUserService userService;

    @Resource
    private IRoleService roleService;

    @Resource
    private IMenuService menuService;

    /**
     * 直接跳转到wt_addJiaose.html界面
     * @return
     */
    @RequiresPermissions("rolepermission")
    @GetMapping("addroleManagepage")
    public String indexSon(Model model){
        List<Menu> menues =null;
        //获取一级菜单
        List<Menu> menuees = menuService.getMenues("0");
        for(Menu menu1:menuees){
            //获取二级、三级菜单
            List<Menu> menuByPid = menuService.getMenuByPid(menu1.getMenuPid());
            menues=menuByPid;
        }
        model.addAttribute("menues", menues);
        return "system/wt_addJiaose";
    }

    /**
     * 跳转到wwt_administrator.html界面
     * @return
     */
    @RequiresPermissions("rolemanage")
    @GetMapping("roleManage")
    public String index(){
        return "system/wt_administrator";
    }

    /**
     * 跳转到wwt_administrator.html界面
     * 无权限
     * @return
     */
    @GetMapping("roleManageaa")
    public String indexaa(){
        return "system/wt_administrator";
    }

    /**
     * 从角色管理页面跳转到wt_addJiaose.html界面
     * @return
     */
    @RequiresPermissions("rolemanage")
    @GetMapping("addroleManage")
    public String addpage(Model model){
        List<Menu> menues =null;
        //获取一级菜单
        List<Menu> menuees = menuService.getMenues("0");
        for(Menu menu1:menuees){
            //获取二级、三级菜单
            List<Menu> menuByPid = menuService.getMenuByPid(menu1.getMenuPid());
            menues=menuByPid;
        }
        model.addAttribute("menues", menues);
        return "system/wt_addJiaose";
    }

    /**
     * 跳转增加页面
     * @return
     */
    @RequiresPermissions("rolemanage")
    @RequestMapping("addRolePage")
    public String addRolePage(Model model){
        List<Menu> menues =null;
        //获取一级菜单
        List<Menu> menuees = menuService.getMenues("0");
      for(Menu menu1:menuees){
            //获取二级、三级菜单
            List<Menu> menuByPid = menuService.getMenuByPid(menu1.getMenuPid());
          menues=menuByPid;
      }
        model.addAttribute("menues", menues);
        return "system/wt_addJiaose";
    }

    /**
     * 1.获取角色管理的角色列表
     * 2.模糊查询
     * 3.分页列表
     * @return
     */
    @RequiresPermissions("rolemanage")
    @ResponseBody
    @PostMapping("listRole")
    public BlbPage listRole(String roleName, String datetime, Model model, int start, int length){
        Page<Role> rolePage = new Page<Role>(start, length);
        User user = ShiroUtils.getUser();
        if(user.getId().equals("1")){
            IPage<Role> page = roleService.page(rolePage, new QueryWrapper<Role>().like("role_name", roleName).like("role_create_date", datetime).eq("id", "1"));
            int count = roleService.count(new QueryWrapper<Role>().like("role_name", roleName).like("role_create_date", datetime).eq("id", "1"));
            return new DataTablePage(count, count, page.getRecords());
        }else {
            IPage<Role> page = roleService.page(rolePage, new QueryWrapper<Role>().like("role_name", roleName).like("role_create_date", datetime).eq("company_id", user.getCompanyId()));
            int count = roleService.count(new QueryWrapper<Role>().like("role_name", roleName).like("role_create_date", datetime).eq("company_id", user.getCompanyId()));
            return new DataTablePage(count, count, page.getRecords());
        }
    }

    /**
     * 更改角色状态
     * @return
     */
    @RequiresPermissions("rolemanage")
    @PostMapping("updateStatus")
    @ResponseBody
    public String updateStatus(@RequestBody JSONObject data){
        String roleid = (String) data.get("roleid");
        String status = (String) data.get("status");
        Integer i = Integer.parseInt(roleid);
        Role role = new Role();
        role.setId(i);
        role.setRoleStatus(status);
        roleService.updateById(role);
        return null;
    }

    /**
     * 单个删除
     * @param data
     * @return
     */
    @RequiresPermissions("rolemanage")
    @PostMapping("delete")
    @ResponseBody
    public String delete(@RequestBody JSONObject data){
        String roleid = (String) data.get("roleid");
        Integer i = Integer.parseInt(roleid);
        roleService.removeById(i);
        menuService.deleteByid(i);
        return null;

    }

    /**
     * 批量删除
     * @param id
     * @return
     */
    @RequiresPermissions("rolemanage")
    @PostMapping("deleteMany")
    @ResponseBody
    public String deleteMany(@RequestParam(value = "ids[]") Integer[] id){
        for(Integer integer: id ){
            roleService.removeById(integer);
            menuService.deleteByid(integer);
        }
        return null;
    }


    /**
     * 修改角色页面
     * @param id
     * @param model
     * @return
     */
    @RequiresPermissions("rolemanage")
    @RequestMapping("updateMenu")
    public String updateMenu(@RequestParam("id") Integer id,Model model){
        Role byId = roleService.getById(id);
        model.addAttribute("byId", byId);
        List<String> menuId = menuService.getMenuId(id);

        List<Menu> menues = null;
        //获取一级菜单
        List<Menu> menuees = menuService.getMenues("0");
        for(Menu menu1:menuees){
            //获取二级、三级菜单
            List<Menu> menuByPid = menuService.getMenuByPid(menu1.getMenuPid());
            for(Menu menu2:menuByPid){
                for(String string: menuId){
                    if(string.equals(menu2.getId())){
                        menu2.setMenuOpt(true);
                    }
                }
                for(Menu menu3:menu2.getList()){
                    for(String string: menuId){
                        if(string.equals(menu3.getId())){
                            menu3.setMenuOpt(true);
                        }
                    }
                    for(Menu menu4:menu3.getList()){
                        for(String string: menuId){
                            if(string.equals(menu4.getId())){
                                menu4.setMenuOpt(true);
                            }
                        }
                    }
                }
            }
            menues = menuByPid;
        }
        model.addAttribute("menues", menues);
        return "system/wt_updateJiaose";
    }

    /**
     * 添加角色用户关联
     * @param id
     * @return
     */
    @RequiresPermissions("rolemanage")
    @PostMapping("addUserRole")
    @ResponseBody
    public String addUserRole(@RequestParam(value = "ids[]") String[] id){
        int a = 1,roleid = 0;
        for(String string : id ){
            if(a == 1){
                roleid = Integer.parseInt(string);
                roleService.delUserAndRole(roleid);
                a++;
            }else {
                roleService.delRoleAndUser(string);
                roleService.addUserAndRole(string, roleid);

            }
        }
        return null;
    }

    /**
     * 创建角色时判断角色名在本公司是否存在
     * @param rolename
     * @return
     */
    @RequiresPermissions("rolemanage")
    @ResponseBody
    @RequestMapping("getRole")
    public Role getRole(String rolename){

        User user = ShiroUtils.getUser();
        Role roleByname = roleService.getRoleByname(rolename, user.getCompanyId());

        return roleByname;

    }

    /**
     * 角色管理分配权限查询用户
     * @param model
     * @param id
     * @return
     */
    @RequiresPermissions("rolemanage")
    @ResponseBody
    @PostMapping("getStaff")
    public ResponseHelp getStaff(Model model, @RequestParam(value = "dd[]") Integer[] id){
        Integer roleId = 0;
        ResponseHelp responseHelp = new ResponseHelp();
        for(Integer i:id){
            roleId = i;
        }
        User user = ShiroUtils.getUser();
        if(user.getId().equals("1")){
            List<User> userByRoleId = roleService.getUserByRoleId();
            List<String> opt = roleService.getOpt(roleId);
            for(User user1:userByRoleId){
                for(String s:opt){
                    if(user1.getId().equals(s)){
                        user1.setUserOpt(true);
                    }
                }
            }
            responseHelp.setData(userByRoleId);
            return responseHelp;
        }else {
            List<User> userStaff = roleService.getUserStaff(user.getCompanyId());
            List<String> userStaffOpt = roleService.getUserStaffOpt(user.getCompanyId(), roleId);
            for(User user1:userStaff){
                for(String s:userStaffOpt){
                    if(user1.getId().equals(s)){
                        user1.setUserOpt(true);
                    }
                }
            }
            responseHelp.setData(userStaff);
            return responseHelp;
        }
    }
}

